/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package GUI;

import FolderChunks.InfoChunk;
import BittorentPackage.*;
import FolderChunks.FilenameChunk;
import UDP.Listener;
import UDP.Sender;
import javax.swing.DefaultListModel;
import javax.swing.JList;
import javax.swing.ListModel;
import managerPeer.Node;
import managerPeer.NodeMap;
import broadcast.*;
import common.function_common;
import common.global;
import hashChunk.SplitFile;
//import hashChunk.Chunk;
import java.io.*;
import java.io.FileNotFoundException;
import java.nio.file.Files;
import java.util.*;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.*;

/**
 *
 * @author ThienLe
 */
public class BittorentLike extends javax.swing.JFrame {

    /**
     * Creates new form BittorentLike
     */
    private BroadcastListener listenner = null;
    private BroadcastSender sender = null;

    public BittorentLike() {
        initComponents();
        sender = new BroadcastSender();
        global.jframMain = (JFrame) this;
        global.nodes = new NodeMap(list_peer);
        global.nodes.updateListPeerOntoGUI();
        ArrayList<String> listDown = function_common.readListFileDownload("src//downloadChunk//listFileDownload.txt");
        ArrayList<String> listShare = function_common.readListFileShare();

        this.list_file_download.setModel(function_common.showArrayList(listDown));
        this.list_file_shared.setModel(function_common.showArrayList(listShare));
        listenner = new BroadcastListener();
        listenner.start();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jTabbedPane1 = new javax.swing.JTabbedPane();
        panel1 = new java.awt.Panel();
        jScrollPane1 = new javax.swing.JScrollPane();
        list_file_download = new javax.swing.JList();
        jScrollPane2 = new javax.swing.JScrollPane();
        jPanel3 = new javax.swing.JPanel();
        jPanel4 = new javax.swing.JPanel();
        DownloadFile = new javax.swing.JButton();
        panel2 = new java.awt.Panel();
        jPanel2 = new javax.swing.JPanel();
        view_path_file = new javax.swing.JTextField();
        buttonBrowseFile = new javax.swing.JButton();
        jScrollPane3 = new javax.swing.JScrollPane();
        list_file_shared = new javax.swing.JList();
        panel3 = new java.awt.Panel();
        jScrollPane4 = new javax.swing.JScrollPane();
        list_peer = new javax.swing.JList();
        buttonRefreshPeer = new javax.swing.JButton();
        jLabel1 = new javax.swing.JLabel();
        buttonCloseFrame = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Bittorent-Like");
        setResizable(false);

        jPanel1.setBackground(new java.awt.Color(255, 255, 255));

        jTabbedPane1.setBackground(new java.awt.Color(255, 255, 255));
        jTabbedPane1.setTabPlacement(javax.swing.JTabbedPane.LEFT);

        jScrollPane1.setBackground(new java.awt.Color(255, 255, 255));
        jScrollPane1.setOpaque(false);

        list_file_download.setName(""); // NOI18N
        jScrollPane1.setViewportView(list_file_download);

        jScrollPane2.setBackground(new java.awt.Color(255, 255, 255));
        jScrollPane2.setOpaque(false);

        jPanel3.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout jPanel3Layout = new javax.swing.GroupLayout(jPanel3);
        jPanel3.setLayout(jPanel3Layout);
        jPanel3Layout.setHorizontalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 738, Short.MAX_VALUE)
        );
        jPanel3Layout.setVerticalGroup(
            jPanel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGap(0, 299, Short.MAX_VALUE)
        );

        jScrollPane2.setViewportView(jPanel3);

        DownloadFile.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        DownloadFile.setText("DownLoad File");
        DownloadFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                DownloadFileActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(DownloadFile, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(DownloadFile, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 45, Short.MAX_VALUE)
        );

        javax.swing.GroupLayout panel1Layout = new javax.swing.GroupLayout(panel1);
        panel1.setLayout(panel1Layout);
        panel1Layout.setHorizontalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane1)
            .addComponent(jScrollPane2, javax.swing.GroupLayout.DEFAULT_SIZE, 738, Short.MAX_VALUE)
            .addComponent(jPanel4, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        panel1Layout.setVerticalGroup(
            panel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel1Layout.createSequentialGroup()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 214, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jPanel4, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 260, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        jTabbedPane1.addTab("Download File", panel1);

        jPanel2.setBackground(new java.awt.Color(255, 255, 255));

        view_path_file.setEditable(false);

        buttonBrowseFile.setBackground(new java.awt.Color(153, 153, 153));
        buttonBrowseFile.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        buttonBrowseFile.setText("Browse");
        buttonBrowseFile.setToolTipText("");
        buttonBrowseFile.setPreferredSize(new java.awt.Dimension(85, 32));
        buttonBrowseFile.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonBrowseFileActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addComponent(view_path_file)
                .addGap(18, 18, 18)
                .addComponent(buttonBrowseFile, javax.swing.GroupLayout.PREFERRED_SIZE, 107, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(buttonBrowseFile, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addComponent(view_path_file)
        );

        jScrollPane3.setViewportView(list_file_shared);

        javax.swing.GroupLayout panel2Layout = new javax.swing.GroupLayout(panel2);
        panel2.setLayout(panel2Layout);
        panel2Layout.setHorizontalGroup(
            panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(panel2Layout.createSequentialGroup()
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 728, Short.MAX_VALUE)
                .addContainerGap())
        );
        panel2Layout.setVerticalGroup(
            panel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(panel2Layout.createSequentialGroup()
                .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane3, javax.swing.GroupLayout.DEFAULT_SIZE, 491, Short.MAX_VALUE)
                .addContainerGap())
        );

        jTabbedPane1.addTab("Shared File", panel2);

        list_peer.setModel(new javax.swing.AbstractListModel() {
            String[] strings = { "Item 1", "Item 2", "Item 3", "Item 4", "Item 5" };
            public int getSize() { return strings.length; }
            public Object getElementAt(int i) { return strings[i]; }
        });
        list_peer.setName("listPeers"); // NOI18N
        jScrollPane4.setViewportView(list_peer);

        buttonRefreshPeer.setBackground(new java.awt.Color(153, 153, 153));
        buttonRefreshPeer.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        buttonRefreshPeer.setText("Join To LAN ");
        buttonRefreshPeer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonRefreshPeerActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout panel3Layout = new javax.swing.GroupLayout(panel3);
        panel3.setLayout(panel3Layout);
        panel3Layout.setHorizontalGroup(
            panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jScrollPane4)
            .addComponent(buttonRefreshPeer, javax.swing.GroupLayout.DEFAULT_SIZE, 738, Short.MAX_VALUE)
        );
        panel3Layout.setVerticalGroup(
            panel3Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, panel3Layout.createSequentialGroup()
                .addComponent(buttonRefreshPeer, javax.swing.GroupLayout.PREFERRED_SIZE, 35, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jScrollPane4, javax.swing.GroupLayout.PREFERRED_SIZE, 515, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        jTabbedPane1.addTab("List Peer", panel3);

        jLabel1.setBackground(new java.awt.Color(255, 255, 255));
        jLabel1.setFont(new java.awt.Font("Cambria", 1, 24)); // NOI18N
        jLabel1.setForeground(new java.awt.Color(51, 207, 30));
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Bittorent - Like");
        jLabel1.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        jLabel1.setOpaque(true);

        buttonCloseFrame.setBackground(new java.awt.Color(255, 255, 255));
        buttonCloseFrame.setIcon(new javax.swing.ImageIcon(getClass().getResource("/GUI/image/exit.png"))); // NOI18N
        buttonCloseFrame.setBorder(null);
        buttonCloseFrame.setOpaque(false);
        buttonCloseFrame.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                buttonCloseFrameActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(buttonCloseFrame, javax.swing.GroupLayout.PREFERRED_SIZE, 84, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addComponent(jTabbedPane1)
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(buttonCloseFrame, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jTabbedPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 545, javax.swing.GroupLayout.PREFERRED_SIZE))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jPanel1, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(0, 2, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void buttonCloseFrameActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonCloseFrameActionPerformed
        // TODO add your handling code here:
        listenner.interrupt();
        listenner = null;
        this.dispose();
    }//GEN-LAST:event_buttonCloseFrameActionPerformed

    private void buttonRefreshPeerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonRefreshPeerActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_buttonRefreshPeerActionPerformed

    private void buttonBrowseFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_buttonBrowseFileActionPerformed
        // TODO add your handling code here:
        final JFileChooser fc = new JFileChooser();
        fc.showOpenDialog(this);
        try {
            //Scanner reader = new Scanner(fc.getSelectedFile());
            //ArrayList<String> liststr = function_common.getAllFolder(global.folderSharedPath);       
            File file = fc.getSelectedFile();
            if (file != null) {
                String path = file.getPath();
                String fileName = file.getName();
                //file.getParent();
                this.view_path_file.setText(path);
                // Split file choose
                SplitFile spFile = new SplitFile();
                String torentShared = spFile.splitFile(file);
                //update list file shared
                ArrayList<String> listFileShared = function_common.readListFileShare();
                DefaultListModel<String> model = new DefaultListModel<String>();
                for (String str : listFileShared) {
                    model.addElement(str);
                }
                //model.addElement(fileName);
                //function_common.writeListFileShare(model);
                this.list_file_shared.setModel(model);


                File torentFile = new File(torentShared);
                if (torentFile.exists()) {
                    int length = (int) torentFile.length();
                    int debug = 1;
                }
            }
        } catch (Exception ex) {
            //Logger.getLogger(BittorentLike.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_buttonBrowseFileActionPerformed

    private void DownloadFileActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_DownloadFileActionPerformed
        // TODO add your handling code here:  
        
        if(this.list_file_download.isSelectionEmpty()){
            JOptionPane.showMessageDialog(this,"Please choose file need downding from list.");
            return;
        }
        final JFileChooser fc = new JFileChooser();
        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
        int returnVal = fc.showOpenDialog(BittorentLike.this);
        if (returnVal == JFileChooser.APPROVE_OPTION) {
            File file = fc.getSelectedFile();
            //This is where a real application would open the file.
            String option = "2";
            String fileSelected = this.list_file_download.getSelectedValue().toString();
            fileSelected = fileSelected.replace(".", global.separatorBittorentTxt);
            Object data = fileSelected;
            BittorentPackageMessage pk = new BittorentPackageMessage(option, data);
            try {
                this.sender.sendBroadcast(pk);
                String pathTorrentFile = fileSelected + "_torent.txt";
                File checkFile = new File("src//FolderTorrentFile//"+pathTorrentFile);
                if(!checkFile.exists()) return;
                FilenameChunk fChunk = function_common.readChunkInfo("src//FolderTorrentFile//"+pathTorrentFile);
                Listener udpListener = new Listener(global.udpPort, fChunk, this, file.getPath());
                udpListener.start();
            } catch (IOException ex) {
                Logger.getLogger(BittorentLike.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }//GEN-LAST:event_DownloadFileActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(BittorentLike.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(BittorentLike.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(BittorentLike.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(BittorentLike.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                new BittorentLike().setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton DownloadFile;
    private javax.swing.JButton buttonBrowseFile;
    private javax.swing.JButton buttonCloseFrame;
    private javax.swing.JButton buttonRefreshPeer;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JScrollPane jScrollPane4;
    private javax.swing.JTabbedPane jTabbedPane1;
    private javax.swing.JList list_file_download;
    private javax.swing.JList list_file_shared;
    private javax.swing.JList list_peer;
    private java.awt.Panel panel1;
    private java.awt.Panel panel2;
    private java.awt.Panel panel3;
    private javax.swing.JTextField view_path_file;
    // End of variables declaration//GEN-END:variables
}
